package com.example.xd.default_call.fragment

import android.content.Context
import android.graphics.ImageFormat
import android.hardware.Camera
import android.hardware.camera2.CameraManager
import android.os.Handler
import android.os.Message
import android.telecom.Call
import android.telecom.InCallService
import android.telecom.VideoProfile
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import com.example.xd.default_call.R
import com.example.xd.default_call.TimeFormatUtil
import com.example.xd.default_call.UIActivity
import com.example.xd.default_call.eventbus_msg.IsSlienceMsg
import com.example.xd.default_call.eventbus_msg.VideoCallOutMsg
import com.example.xd.default_call.toast
import com.example.xd.default_call.weight.DCP_Dialog
import com.example.xd.default_call.weight.floating.FloatWindowManager
import com.example.xd.default_call.weight.surface.VideoSurfaceDelegate
import com.example.xd.default_call.weight.surface.VideoSurfaceTexture
import com.example.xd.default_call.weight.surface.VideoSurfaceTextureImpl
import kotlinx.android.synthetic.main.fragment_call_out.*
import kotlinx.android.synthetic.main.fragment_call_video_in.*
import kotlinx.android.synthetic.main.fragment_call_video_out.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @auther XuDan on 2020/8/13.
 */
class Call_Video_Out_Fragment : BaseFragment(), View.OnClickListener, VideoSurfaceDelegate {

    var time: Long = 0
    var mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                time++
                video_out_time_tv.setText("通话时长：" + TimeFormatUtil.instance.stringForTime(time))
                val obtain = Message.obtain()
                obtain.what = 1
                sendMessageDelayed(obtain, 1000)
            }
        }
    }

    override fun registerMethod() {
        EventBus.getDefault().register(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_call_video_out

    }

    lateinit var remote_texture: VideoSurfaceTextureImpl
    lateinit var local_texture: VideoSurfaceTextureImpl
    override fun initViews(view: View) {
        video_out_cut_img.setOnClickListener(this)
        video_out_change_img.setOnClickListener(this)
        video_out_float_img.setOnClickListener(this)
        video_out_silence_img.setOnClickListener(this)
        video_out_close_img.setOnClickListener(this)
        video_out_tv_change.setOnClickListener(this)
        video_out_tv_keyboard.setOnClickListener(this)
        remote_texture =
            VideoSurfaceTextureImpl(true, VideoSurfaceTexture.SURFACE_TYPE_REMOTE)
        local_texture =
            VideoSurfaceTextureImpl(true, VideoSurfaceTexture.SURFACE_TYPE_LOCAL)
        remote_texture.attachToTextureView(video_out_remote_sv)
        local_texture.attachToTextureView(video_out_my_sv)
        remote_texture.setDelegate(this)
        local_texture.setDelegate(this)
    }

    lateinit var call: Call
    lateinit var myCallBack: MyCallBack

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun videoOutStart(msg: VideoCallOutMsg) {
        call = msg.call
        myCallBack = MyCallBack()
        call.registerCallback(myCallBack)
    }

    override fun unRegisterMethod() {
        call.unregisterCallback(myCallBack)
        videoCall?.unregisterCallback(videoCallBack)
        EventBus.getDefault().unregister(this)
    }

    override fun onResume() {
        super.onResume()
    }

    var isPreviaFace = true
    var isVideoCall = true
    var isSlience = false
    var isOpenVideo = true
    override fun onClick(v: View) {
        when (v) {
            video_out_cut_img -> {
                call.disconnect()
            }
            video_out_change_img -> {//前置为1后置为0
                isPreviaFace = !isPreviaFace
                if (isPreviaFace) {
                    videoCall?.setCamera(cameraManager.cameraIdList[1])//前置
                    videoCall?.setDeviceOrientation(0)
                } else {
                    videoCall?.setCamera(cameraManager.cameraIdList[0])//后置
                    videoCall?.setDeviceOrientation(0)
                }
            }
            video_out_silence_img -> {
                isSlience = !isSlience
                EventBus.getDefault().post(IsSlienceMsg(isSlience))
            }
            video_out_float_img -> {
                FloatWindowManager.getInstance().applyOrShowFloatWindow(mActivity, remote_texture)
                mActivity.moveTaskToBack(true)
            }
            video_out_close_img -> {
                isOpenVideo = !isOpenVideo
                if (isOpenVideo) {//双方都能看到对方
                    toast(mActivity, "打开摄像头")
                    videoCall?.setPreviewSurface(local_texture.savedSurface)//用户当前捕获的预览
                } else {//我能看到对方，对方看不到我
                    toast(mActivity, "关闭摄像头")
                    videoCall?.setPreviewSurface(null)//用户当前捕获的预览
                }
            }
            video_out_tv_change -> {
                isVideoCall = !isVideoCall
                if (isVideoCall) {
                    videoCall?.sendSessionModifyRequest(VideoProfile(VideoProfile.STATE_BIDIRECTIONAL))
                    video_out_remote_sv.visibility = View.VISIBLE
                    video_out_my_sv.visibility = View.VISIBLE
                    videoCall?.setDisplaySurface(remote_texture.savedSurface)//显示远程接收视频
                    videoCall?.setPreviewSurface(local_texture.savedSurface)//用户当前捕获的预览
                } else {
                    videoCall?.sendSessionModifyRequest(VideoProfile(VideoProfile.STATE_AUDIO_ONLY))
                    video_out_remote_sv.visibility = View.GONE
                    video_out_my_sv.visibility = View.GONE
                }
            }
            video_out_tv_keyboard -> {
            }
        }
    }

    var videoCall: InCallService.VideoCall? = null
    lateinit var cameraManager: CameraManager
    lateinit var videoCallBack: MyVideoCallBack


    inner class MyCallBack : Call.Callback() {
        override fun onStateChanged(call: Call, state: Int) {
            super.onStateChanged(call, state)
            when (state) {
                Call.STATE_ACTIVE -> {
                    video_out_ll.visibility = View.VISIBLE

                    val obtain = Message.obtain()
                    obtain.what = 1
                    mHandler.sendMessage(obtain)

                    cameraManager =
                        mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
                    videoCall = call.videoCall
                    videoCallBack = MyVideoCallBack()
                    videoCall?.registerCallback(videoCallBack)
                    videoCall?.setCamera(cameraManager.cameraIdList[1])//默认后置
                    videoCall?.setDeviceOrientation(0)
                    videoCall?.setDisplaySurface(remote_texture.savedSurface)//显示远程接收视频
                    videoCall?.setPreviewSurface(local_texture.savedSurface)//用户当前捕获的预览
                    videoCall?.requestCallDataUsage()
                    videoCall?.requestCameraCapabilities()
                }
                Call.STATE_DISCONNECTED -> {
                    video_out_time_tv.text = "通话结束"
                    mHandler.removeCallbacksAndMessages(null)
                    mActivity.finish()
                }
            }
        }

        override fun onVideoCallChanged(call: Call?, videocall: InCallService.VideoCall?) {
            super.onVideoCallChanged(call, videoCall)

        }
    }

    inner class MyVideoCallBack : InCallService.VideoCall.Callback() {
        override fun onVideoQualityChanged(videoQuality: Int) {
        }

        override fun onCallDataUsageChanged(dataUsage: Long) {
        }

        override fun onPeerDimensionsChanged(width: Int, height: Int) {
        }

        override fun onSessionModifyResponseReceived(
            status: Int,
            requestedProfile: VideoProfile?,//发送给对等设备的原始请求。
            responseProfile: VideoProfile?//对等设备进行的实际配置文件更改
        ) {//接收到对先前发送给对等设备的会话修改请求的响应时调用
            Log.i("xd---", "onSessionModifyResponseReceived===" + responseProfile?.videoState)

        }

        override fun onSessionModifyRequestReceived(videoProfile: VideoProfile?) {//接收到来自对等设备的会话修改请求时调用
            when (videoProfile?.videoState) {
                VideoProfile.STATE_AUDIO_ONLY -> {
                    toast(mActivity, "对方切换为语音通话")
                    video_out_remote_sv.visibility = View.GONE
                    video_out_my_sv.visibility = View.GONE
                    videoCall?.sendSessionModifyRequest(videoProfile)
                    videoCall?.sendSessionModifyResponse(videoProfile)
                }
                VideoProfile.STATE_BIDIRECTIONAL -> {
                    Log.i("xd---", "对方切换为视频通话")
                    val dcpDialog = DCP_Dialog(mActivity)
                    dcpDialog.setDialogOkListener(object : DCP_Dialog.DialogListener {
                        override fun dialogOk() {
                            videoCall?.sendSessionModifyRequest(videoProfile)
                            videoCall?.sendSessionModifyResponse(videoProfile)
                            video_out_remote_sv.visibility = View.VISIBLE
                            video_out_my_sv.visibility = View.VISIBLE
                            videoCall?.setDisplaySurface(remote_texture.savedSurface)//显示远程接收视频
                            videoCall?.setPreviewSurface(local_texture.savedSurface)//用户当前捕获的预览
                            dcpDialog.dismiss()

                        }

                        override fun dialogCancle() {
                            call.disconnect()
                            dcpDialog.dismiss()
                        }

                    })
                    dcpDialog.show()
                }
            }
        }

        override fun onCameraCapabilitiesChanged(cameraCapabilities: VideoProfile.CameraCapabilities?) {
        }

        override fun onCallSessionEvent(event: Int) {
        }

    }

    var camera: Camera? = null
    var isFit = true
    override fun onSurfaceClick(videoCallSurface: VideoSurfaceTexture?) {
        isFit = !isFit
        when (videoCallSurface) {
            remote_texture -> {
                toast(mActivity, "remote_texture")
            }
            local_texture -> {
                if (isFit) {

                } else {

                }
                toast(mActivity, "local_texture")
            }
        }
    }

    override fun onSurfaceCreated(videoCallSurface: VideoSurfaceTexture?) {
        Log.i("xd---", "onSurfaceCreated")
        when (videoCallSurface) {
            remote_texture -> {
                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
                camera?.setDisplayOrientation(90)
                camera?.setPreviewTexture(video_out_remote_sv.surfaceTexture)
                val parameters = camera!!.parameters
                parameters.setPictureSize(1920, 1080)
                parameters.previewFormat = ImageFormat.NV21
                camera?.parameters = parameters
                camera?.startPreview()
            }
            local_texture -> {
            }
        }

    }

    override fun onSurfaceReleased(videoCallSurface: VideoSurfaceTexture?) {
        Log.i("xd---", "onSurfaceReleased")

    }

    override fun onSurfaceDestroyed(videoCallSurface: VideoSurfaceTexture?) {
        Log.i("xd---", "onSurfaceDestroyed")

        when (videoCallSurface) {
            remote_texture -> {
                camera?.stopPreview()
                camera?.release()
                camera = null
            }
            local_texture -> {
            }
        }

    }
}